<template>
	<a-card :bordered="false" class="mb-3">
		<div class="flex justify-between items-start">
			<a-form
				ref="searchFormRef"
				name="advanced_search"
				:model="searchFormState"
				class="ant-advanced-search-form"
				style="width: calc(100% - 100px)"
			>
				<a-space :size="16" class="flex-wrap">
					<a-form-item label="人员范围" name="data" class="mb-0">
						<a-select
							v-model:value="searchFormState.data"
							style="width: 180px"
							placeholder="请选择"
							@change="onDepartmentChange"
						>
							<a-select-option v-if="store.roleAuthMap.self" value="1">本人</a-select-option>
							<a-select-option v-if="store.roleAuthMap.dept" value="2">本部门</a-select-option>
							<a-select-option v-if="store.roleAuthMap.deptAndSub" value="3">本部门及下级部门</a-select-option>
							<a-select-option v-if="store.roleAuthMap.all" value="4">全企业</a-select-option>
							<a-select-option v-if="store.roleAuthMap.dept" value="5" @click="onCustomClick">自定义</a-select-option>
						</a-select>
					</a-form-item>
					<a-form-item v-if="searchFormState.data === '5'" name="tempPersonIds" class="mb-0">
						<a-tree-select
							v-model:value="searchFormState.tempPersonIds"
							style="width: 360px"
							:tree-data="orgUserTreeData"
							tree-checkable
							allow-clear
							:show-checked-strategy="SHOW_PARENT"
							placeholder="请选择人员范围"
							tree-node-filter-prop="label"
							:fieldNames="fieldNames"
							max-tag-count="responsive"
							:dropdownMatchSelectWidth="false"
							treeNodeFilterProp="name"
							@change="onPersonChange"
						/>
					</a-form-item>
					<a-form-item label="时间" name="timeRange" class="mb-0">
						<a-range-picker
							v-model:value="searchFormState.timeRange"
							:disabled-date="disabledDate"
							allowClear
							style="width: 100%"
							@calendarChange="onCalendarChange"
						/>
					</a-form-item>
					<a-form-item label="所有来源" name="sourceId" class="mb-0">
						<a-select
							v-model:value="searchFormState.sourceId"
							placeholder="请选择"
							:options="customerFromOptions"
							style="width: 196px"
							@change="onSourceChange"
						></a-select>
					</a-form-item>
					<a-button @click="reset">重置</a-button>
				</a-space>
			</a-form>
		</div>
	</a-card>
	<a-spin :spinning="onLoading" size="large" style="min-height: 70vh">
		<a-card :loading="onLoading" :bordered="false" class="mb-3">
			<div class="flex flex-wrap">
				<div
					v-for="(item, index) in fieldList"
					:key="index"
					class="mx-4 my-3 p-2 w-[250px] flex flex-col justify-center border-[1px] border-solid border-zinc-300 rounded-md cursor-pointer"
				>
					<div class="ml-4 my-2 text-[16px] flex justify-between items-center">
						<span>{{ item.title }}</span>
						<a-tooltip>
							<template #title>{{ item.tip }}</template>
							<question-circle-outlined
								class="mr-3"
								:style="{
									color: '#bbb'
								}"
							/>
						</a-tooltip>
					</div>
					<div class="ml-4 mb-4 text-[17px]">{{ statisticsData[item.field] || item.defaultVal }}</div>
				</div>
			</div>
		</a-card>
		<a-card :loading="onLoading" :bordered="false" class="mb-3">
			<div class="section-title">明细数据</div>
			<view class="flex justify-end"
				><a-button type="primary" @click="onExport">
					<template #icon><export-outlined /></template>
					导出
				</a-button></view
			>
			<s-table
				ref="table"
				:columns="columns"
				:data="loadData"
				:alert="false"
				bordered
				:showPagination="false"
				:row-key="(record) => record.id"
				:tool-config="toolConfig"
			>
				<template #headerCell="{ column }">
					<template v-for="(item, index) in fieldList">
						<template v-if="column.dataIndex === item.field">
							<span :key="index">
								<span>{{ item.title }}</span>
								<a-tooltip>
									<template #title>{{ item.tip }}</template>
									<question-circle-outlined
										class="ml-1"
										:style="{
											color: '#bbb'
										}"
									/>
								</a-tooltip>
							</span>
						</template>
					</template>
				</template>
			</s-table>
		</a-card>
	</a-spin>
</template>
<script setup>
	import { TreeSelect } from 'ant-design-vue'
	import statisticsApi from '@/api/biz/statisticsApi'
	import downloadUtil from '@/utils/downloadUtil'
	import dayjs from 'dayjs'
	import { globalStore } from '@/store'
	import customerSourceApi from '@/api/biz/crm/customerSourceApi'
	import tool from '@/utils/tool'

	const store = globalStore()

	const fieldList = [
		{ field: 'clueNum', title: '线索量', tip: '线索量', defaultVal: 0 },
		{ field: 'customerNum', title: '客户量', tip: '客户量', defaultVal: 0 },
		{ field: 'callNum', title: '电话呼出量', tip: '选择条件范围内，呼出电话的次数，包括接听和未接听的', defaultVal: 0 },
		{ field: 'callThroughNum', title: '电话接通量', tip: '选择条件范围内，呼出电话的次数有接通的', defaultVal: 0 },
		{
			field: 'validThroughNum',
			title: '有效接通量',
			tip: '选择条件范围内，达到系统设定的有效通话的总次数',
			defaultVal: 0
		},
		{
			field: 'callDuration',
			title: '通话时长',
			tip: '选择条件范围内，所有通话时长的总和为通话总时长',
			defaultVal: '00小时00分00秒'
		},
		{
			field: 'aveCallDuration',
			title: '平均通话时长',
			tip: '选择条件范围内，平均每次通话的时间',
			defaultVal: '00小时00分00秒'
		},
		{
			field: 'validCallDuration',
			title: '有效通话时长',
			tip: '选择条件范围内，达到系统设定的有效通话的累计时长',
			defaultVal: '00小时00分00秒'
		},
		{ field: 'callThroughRate', title: '电话接通率', tip: '电话接通量/电话呼出量', defaultVal: '0.00%' },
		{ field: 'validThroughRate', title: '有效电话率', tip: '有效接通量/电话接通量', defaultVal: '0.00%' },
		{ field: 'newWxNum', title: '微信添加量', tip: '有添加微信的客户数', defaultVal: 0 },
		{ field: 'intentCustomerNum', title: '意向客户量', tip: '跟进后客户等级标记为A、B、C的客户数量', defaultVal: 0 },
		{ field: 'intentRate', title: '意向客户产出率', tip: '意向客户量/总客户量', defaultVal: '0.00%' },
		{ field: 'dealNum', title: '成交量', tip: '合同交易完成', defaultVal: 0 }
	]

	const onLoading = ref(true)

	onMounted(() => {
		getStatistics()
	})

	const getParams = () => {
		const { data, personIds, timeRange, sourceId } = searchFormState
		return {
			data,
			dataStr: personIds.join(','),
			stime: timeRange[0]?.format('YYYY-MM-DD'),
			etime: timeRange[1]?.format('YYYY-MM-DD'),
			sourceId
		}
	}

	const statisticsData = reactive({})
	const getStatistics = () => {
		onLoading.value = true
		const params = getParams()
		statisticsApi.getStatistics(params).then((data) => {
			Object.assign(statisticsData, data)
			onLoading.value = false
		})
	}

	let searchFormState = reactive({
		data: store.roleAuthMap.dept ? '2' : '1',
		tempPersonIds: [],
		personIds: [],
		timeRange: [dayjs(), dayjs()],
		sourceId: null
	})
	const searchFormRef = ref()

	const onDepartmentChange = (value) => {
		nextTick(() => {
			if (value !== '5') {
				onCustomClick()
				getStatistics()
			}
		})
	}

	const onCustomClick = () => {
		searchFormState.tempPersonIds = []
		searchFormState.personIds = []
	}

	const SHOW_PARENT = TreeSelect.SHOW_PARENT
	const fieldNames = {
		label: 'name',
		value: 'id'
	}
	const orgUserTreeData = ref(store.authDeptList)
	const onPersonChange = (value, label, extra) => {
		searchFormState.personIds = tool.getAllBottomPersonIds(extra.allCheckedNodes)
		getStatistics()
	}

	const dates = ref()
	const disabledDate = (current) => {
		if (!dates.value || dates.value.length === 0) {
			return false
		}
		const tooLate = dates.value[0] && current.diff(dates.value[0], 'days') > 90
		const tooEarly = dates.value[1] && dates.value[1].diff(current, 'days') > 90
		return tooEarly || tooLate
	}
	const onCalendarChange = (val) => {
		dates.value = val
		nextTick(() => {
			if (val.length === 2 && val[1]) {
				getStatistics()
			}
		})
	}

	// 来源
	const customerFromOptions = ref([])
	customerSourceApi.list().then((res) => {
		customerFromOptions.value = res.map((item) => {
			return {
				value: item.id,
				label: item.name
			}
		})
	})
	const onSourceChange = (value) => {
		getStatistics()
	}

	// 重置
	const reset = () => {
		searchFormState.tempPersonIds = []
		searchFormState.personIds = []
		searchFormRef.value.resetFields()
		getStatistics()
	}

	// 导出
	const onExport = () => {
		const params = getParams()
		statisticsApi.exportList(params).then((res) => {
			downloadUtil.resultDownload(res)
		})
	}

	// 表格
	const table = ref()
	const toolConfig = { refresh: false, height: false, columnSetting: false, striped: false }
	const columns = [
		{
			title: '时间',
			dataIndex: 'day'
		},
		{
			title: '线索量',
			dataIndex: 'clueNum',
			customRender: ({ text }) => text || 0
		},
		{
			title: '客户量',
			dataIndex: 'customerNum',
			customRender: ({ text }) => text || 0
		},
		{
			title: '电话呼出量',
			dataIndex: 'callNum',
			customRender: ({ text }) => text || 0
		},
		{
			title: '电话接通量',
			dataIndex: 'callThroughNum',
			customRender: ({ text }) => text || 0
		},
		{
			title: '有效接通量',
			dataIndex: 'validThroughNum',
			customRender: ({ text }) => text || 0
		},
		{
			title: '通话时长',
			dataIndex: 'callDuration',
			customRender: ({ text }) => text || '00小时00分00秒'
		},
		{
			title: '平均通话时长',
			dataIndex: 'aveCallDuration',
			customRender: ({ text }) => text || '00小时00分00秒'
		},
		{
			title: '有效通话时长',
			dataIndex: 'validCallDuration',
			customRender: ({ text }) => text || '00小时00分00秒'
		},
		{
			title: '电话接通率',
			dataIndex: 'callThroughRate',
			customRender: ({ text }) => text || '0.00%'
		},
		{
			title: '有效电话率',
			dataIndex: 'validThroughRate',
			customRender: ({ text }) => text || '0.00%'
		},
		{
			title: '微信添加量',
			dataIndex: 'newWxNum',
			customRender: ({ text }) => text || 0
		},
		{
			title: '意向客户量',
			dataIndex: 'intentCustomerNum',
			customRender: ({ text }) => text || 0
		},
		{
			title: '意向客户产出率',
			dataIndex: 'intentRate',
			customRender: ({ text }) => text || '0.00%'
		},
		{
			title: '成交量',
			dataIndex: 'dealNum',
			customRender: ({ text }) => text || 0
		}
	]
	const loadData = (parameter) => {
		const params = getParams()
		return statisticsApi.getList({ ...parameter, ...params }).then((data) => {
			return data
		})
	}
</script>

<style lang="less" scoped>
	.section-title {
		position: relative;
		margin: 0 0 12px 0;
		padding-left: 18px;
		font-size: 18px;
		font-weight: 600;
		line-height: 1;
		&::after {
			content: '';
			position: absolute;
			left: 0;
			top: 0;
			width: 5px;
			height: 100%;
			border-radius: 1px;
			background: var(--primary-7);
		}
	}
</style>
